package com.leetao.netty.core;

import com.leetao.netty.handler.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 处理器
 *
 * @author 菅江晖
 * @date 2021/4/15 - 16:11
 */
@Component
@io.netty.channel.ChannelHandler.Sharable
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    ChannelHandler channelHandler;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //接收到消息
        channelHandler.message(ctx, msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //建立连接
        channelHandler.connected(ctx);
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //与客户端断开连接
        channelHandler.disconnected(ctx);
        super.channelInactive(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //当前通道处理器已删除
        channelHandler.close(ctx);
        super.handlerRemoved(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 首次连接是FullHttpRequest，处理参数 by zhengkai.blog.csdn.net
        if (msg instanceof FullHttpRequest) {
            channelHandler.init(ctx, (FullHttpRequest) msg);
        }

        super.channelRead(ctx, msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //出现异常
        channelHandler.exception(ctx,cause);
        super.exceptionCaught(ctx, cause);
    }
}
